<?php

namespace app\controller\property\piles;

use think\App;
use app\controller\property\Base;
use think\exception\ValidateException;
use app\validate\piles\PilesOrderValidate;
use app\common\repositories\piles\PilesOrderRepository;
use app\common\repositories\piles\PilesBasicRepository;


class PilesOrder extends Base
{
    protected $repository;

    public function __construct(App $app, PilesOrderRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
        $this->assign([
            'addAuth' => property_auth('propertyPilesOrderAdd'),
            'editAuth' => property_auth('propertyPilesOrderEdit'),
            'delAuth' => property_auth('propertyPilesOrderDel'),
            'detailAuth' => property_auth('propertyPilesOrderDetail'),
            'refundAuth' => property_auth('propertyPilesOrderRefund')
        ]);
    }


    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'keywords' => '',
                'piles_id' => '',
                'port_no' => '',
                'time' => ''
            ]);
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        /** @var PilesBasicRepository $pilesBasicRepository */
        $pilesBasicRepository = app()->make(PilesBasicRepository::class);
        $pilesData = $pilesBasicRepository->getPilesData($this->request->propertyId, ['is_show' => 1]);
        return $this->fetch('piles/order/list', [
            'pilesData' => $pilesData,
        ]);
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'order_no' => '',
                'piles_id' => '',
                'port_no' => '',
                'pay_status' => '',
                'pay_price' => '',
                'pay_type' => '',
                'work_time' => '',
                'remark' => '',
                'full_auto_close' => '',
            ]);
            validate(PilesOrderValidate::class)->scene('add')->check($param);
            if ($this->repository->propertyFieldExists($this->request->propertyId, 'order_no', $param['order_no'])) {
                return $this->error('订单号：' . $param['order_no'] . ' 已存在');
            }
            try {
                $res = $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加充电订单失败', $e);
                return $this->error('网络失败');
            }
        } else {
            /** @var PilesBasicRepository $pilesBasicRepository */
            $pilesBasicRepository = app()->make(PilesBasicRepository::class);
            $pilesData = $pilesBasicRepository->getPilesData($this->request->propertyId, ['is_show' => 1]);
            $orderNo = $this->repository->getPilesOrderNo($this->request->propertyId);
            return $this->fetch('piles/order/add', [
                'orderNo' => $orderNo,
                'pilesData' => $pilesData,
            ]);
        }

    }


    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'order_no' => '',
                'port_no' => '',
                'user_id' => '',
                'pay_status' => '',
                'pay_price' => '',
                'pay_type' => '',
                'work_time' => '',
                'remark' => '',
                'full_auto_close' => '',
            ]);
            validate(PilesOrderValidate::class)->scene('edit')->check($param);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('修改充电订单失败', $e);
                return $this->error('网络错误' . $e->getMessage() . $e->getFile() . $e->getLine());
            }
        } else {
            return $this->fetch('piles/order/edit', [
                'info' => $info,
            ]);
        }
    }

    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除充电订单失败', $e);
            return $this->error('网络失败');
        }
    }

    /**
     * 订单详情
     */
    public function detail()
    {
        $id = $this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        return $this->fetch('piles/order/detail', [
            'info' => $info
        ]);
    }

    public function refund()
    {
        $id = $this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $orderInfo = $this->repository->get($id);
        if (!$orderInfo || $orderInfo['pay_status'] != 1) {
            return $this->error('数据不存在');
        }
        $refundPrice = bcsub($orderInfo['pay_price'], $orderInfo['actual_amount'], 2);
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'refund_price' => ''
            ]);
            if ($refundPrice < $param['refund_price']) {
                return $this->error('退款金额不足' . $param['refund_price'] . '元');
            }
            try {
                $res = $this->repository->refund($param['refund_price'], $orderInfo, $this->request->userId);
                if ($res) {
                    return $this->success('操作成功');
                } else {
                    return $this->error('操作失败');
                }
            } catch (\Exception $e) {
                exception_log('订单退款失败', $e);
                return $this->error('网络错误');
            }
        } else {
            return $this->fetch('piles/order/refund', [
                'refundPrice' => $refundPrice
            ]);
        }
    }

}